package com.isoft.illustrationsdraw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;

import com.isoft.illustrationsdraw.entity.User;
import com.isoft.illustrationsdraw.mapper.UserMapper;
import com.isoft.illustrationsdraw.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User getOrCreateUser(String email) {
        // 直接通过 email 查询用户，如果用户存在，返回其 ID
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User user = getOne(wrapper);

        if (user != null) {
            // 如果用户已存在，返回用户 ID
            return user;
        } else {
            // 如果用户不存在，创建新用户并返回其 ID
            user = new User();
            user.setEmail(email);

            boolean saved = save(user);  // 保存用户
            if (saved) {
                return user;  // 返回新创建的用户 ID
            } else {
                throw new RuntimeException("Failed to create user.");  // 创建失败时抛出异常
            }
        }
    }

    @Override
    public Long getIdByEmail(String email) {
        // 使用 getOne 方法查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User user = getOne(wrapper);
        
        return (user != null) ? user.getId() : null;  // 返回用户 ID，如果用户不存在返回 null
    }

    @Override
    public List<User> getUserByNickname(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("nickname", name);
        return list(wrapper);
    }
}
